package com.shi.yoyoshop.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shi.yoyoshop.bean.Goods;
import com.shi.yoyoshop.bean.Item;
import com.shi.yoyoshop.bean.Order;
import com.shi.yoyoshop.bean.User;
import com.shi.yoyoshop.service.GoodsService;
import com.shi.yoyoshop.service.ItemService;
import com.shi.yoyoshop.service.OrderService;
import com.shi.yoyoshop.service.UserService;
import com.shi.yoyoshop.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private ItemService itemService;

    @Resource
    private UserService userService;

    /**
     * 前台查看我的订单
     *
     * @param request
     * @return
     */
    @GetMapping("/index/order")
    public String myOrder(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (ObjectUtils.isEmpty(user)) {
            request.setAttribute("msg", "请先登录");
            return "/index/login.jsp";
        }
        // 获取当前用户的订单item
        List<Order> orderList = orderService.getOrderListByUserId(user.getId());
        if (!CollectionUtils.isEmpty(orderList)) {
            orderList.forEach(order -> {
                // 获取当前订单下对应的itemList
                List<Item> itemList = itemService.getItemListByOrderId(order.getId());
                order.setItemList(itemList);
                if (!CollectionUtils.isEmpty(itemList)) {
                    itemList.forEach(item -> {
                        Goods goods = goodsService.getGoodsById(item.getGoodId());
                        item.setGoods(goods);
                    });
                }
            });
        }
        request.setAttribute("flag", 3);
        request.setAttribute("orderList", orderList);
        return "/index/order.jsp";
    }

    /**
     * 提交订单
     *
     * @param request
     * @return
     */
    @GetMapping("/index/placeOrder")
    public String submitOrder(HttpServletRequest request) {
        Order order = (Order) request.getSession().getAttribute("order");
        List<Item> itemList = order.getItemList();
        // 提交订单
        // 判断是否每个商品都库存充足
        for (Item item : itemList) {
            Integer goodId = item.getGoodId();
            Integer amount = item.getAmount();
            Goods goods = goodsService.getGoodsById(goodId);
            // 库存不足
            if (goods.getStock() < amount) {
                request.setAttribute("msg", goods.getName() + ": 库存不足");
                return "redirect:/index/cart";
            }
        }

        // 对goods的库存进行修改
        for (Item item : itemList) {
            Integer goodId = item.getGoodId();
            Integer amount = item.getAmount();
            Goods goods = goodsService.getGoodsById(goodId);
            goods.setStock(goods.getStock() - amount);
            // 修改goods的库存量
            goodsService.modifyGoodsById(goods);
        }
        // 修改 order信息，并添加order
        // 订单状态 0表示删除，1表示未付款，2表示已付款，3表示配送中，4表示已完成
        // 支付方式0表示未支付 1表示微信支付，2表示支付宝支付，3表示货到付款
        // 下单时间
        order.setStatus(1);
        order.setPaytype(0);
        order.setSystime(new Date());
        orderService.saveOrder(order);
        // 填充item的orderId,然后添加item到数据库
        for (Item item : order.getItemList()) {
            item.setOrderId(order.getId());
            itemService.saveItem(item);
        }
        // 提交订单，清空购物车
        order.setItemList(new ArrayList<>());
        order.setAmount(0);
        order.setTotal(0.0);
        request.getSession().setAttribute("order", order);
        return "/index/pay.jsp";
    }

    /**
     * 后台获取 不同状态的分页订单
     *
     * @param request
     * @param status
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/admin/orderList")
    public String searchOrderListWithPage(HttpServletRequest request, Integer status, Integer page, Integer size) {
        IPage<Order> pageInfo = orderService.getOrderListByStatusWithPage(new Page<Order>(page, size), status);
        List<Order> orderList = pageInfo.getRecords();
        if (!CollectionUtils.isEmpty(orderList)) {
            orderList.forEach(order -> {
                User user = userService.getUserById(order.getUserId());
                order.setUser(user);
                // 获取当前订单下对应的itemList
                List<Item> itemList = itemService.getItemListByOrderId(order.getId());
                order.setItemList(itemList);
                if (!CollectionUtils.isEmpty(itemList)) {
                    itemList.forEach(item -> {
                        Goods goods = goodsService.getGoodsById(item.getGoodId());
                        item.setGoods(goods);
                    });
                }
            });
        }
        String pageTool = PageUtil.getPageTool(request, pageInfo.getTotal(), page, size);
        request.setAttribute("flag", 1);
        request.setAttribute("status", status);
        request.setAttribute("pageTool", pageTool);
        request.setAttribute("orderList", orderList);
        return "/admin/order_list.jsp";
    }

    @GetMapping("/admin/orderOperate")
    public String updateOrderStatus(String operate, Integer id, Integer status) {
        Order order = orderService.getOrderById(id);
        if ("send".equals(operate)) {
            order.setStatus(3);
        }
        if ("finish".equals(operate)) {
            order.setStatus(4);
        }
        if ("delete".equals(operate)) {
            order.setStatus(0);
        }
        orderService.updateOrderById(order);
        return "redirect:/admin/orderList?status=" + status + "&page=1&size=6";
    }
}
